<template>
    <div class="main-todo">
        <input type="text" 
                class="add-todo" 
                placeholder="what to do?"
                @keydown.enter="addTodo" 
                autofocus
                v-model.trim="content"/>
        <todo-item v-for="(item, index) in filterData" :key="index" :con="item" @deleteWork="deleteWork"/>
        <todo-info :total="total" @changeIndex="changeIndex" @clear="clear"/>
    </div>
</template>

<script>
import TodoItem from './com/TodoItem.vue'
import TodoInfo from './com/TodoInfo.vue'
export default {
    name: 'MainTodo',
    components: {
        TodoItem,
        TodoInfo
    },
    data() {
        return {
            content: '',
            todoData: [],
            total: 0,
            statu: 0
        }
    },
    methods: {
        // 添加事件
        addTodo() {
            if(this.content.length <= 0) {
                this.content = ''
                alert('请输入内容')
                return
            }
            const obj = {
                id: this.todoData.length,
                content: this.content,
                completed: false
            }
            this.todoData.unshift(obj)
            this.content = ''
        },
        // 删除事件
        deleteWork(id) {
            this.todoData = this.todoData.filter(item => item.id !== id)
        },
        // 改变事件
        changeIndex(id) {
            this.statu = id
        },
        // 清理数据
        clear() {
            this.todoData = this.todoData.filter(item => item.completed == false)
        } 
    },
    watch: {
        todoData: {
            deep: true,
            handler() {
                this.total = this.todoData.filter(item => item.completed == false).length
            }
        }
    },
    computed: {
        filterData() {
            switch(this.statu) {
                case 0:
                    return this.todoData
                    break
                case 1:
                    return this.todoData.filter(item => item.completed == false)
                    break
                case 2:
                    return this.todoData.filter(item => item.completed == true)        
            }
        }
    }
}
</script>

<style lang="less" scoped>
.main-todo {
    width: 600px;
    margin: 0 auto;
    box-shadow: 0 0 5px #fff;
    background-color: #fff;
    .add-todo {
        width: 100%;
        padding: 16px;
        border: none;
        outline: none;
        box-sizing: border-box;
        font-size: 24px;
        font-family: inherit;
        font-weight: inherit;
    }
}
</style>